//
//  AmountActivityModel.swift
//  DaRings
//
//  Created by 尹琼 on 2023/2/23.
//

import UIKit
import SQLite
import HandyJSON
import SwiftDate
import SQLiteValueExtension
import MYModule

/// 活动量
open class AmountActivityModel: NSObject, MYSQLiteTableiabe, FullDaySQLite, HandyJSON {
    
    public var adress: String = ""
    
    public var id: Int64 = 0
    
    public var date: Date = Date().sqlDate()
    
    /// 活动量 （整天 1440 个）
    public var activitys: [Int] = []
    
    var updateTime: Double = 0
    
    public var isEmpty: Bool {
        
        let activitys = activitys.filter({$0 > 0 })
        return activitys.isEmpty
    }
    
    required public override init() {}
    
    /// 一次完整睡眠的睡眠活动状态
    public var fullActicitys: [Int] {
        
        guard let sleepModel = SleepModel.day(date: date) else {
            return (0 ..< 1440).map { _ in 0 }
        }
        
        var activitys = self.activitys
        if activitys.count < 1440 {
            let zeros = (activitys.count ..< 1440).map { _ in 0 }
            activitys.append(contentsOf: zeros)
        }
        
        // 睡眠开始时间
        guard let fallAsleepDate = sleepModel.fallAsleepDate,
              let awakeDate = sleepModel.awakeDate else  {
            return []
        }
        
        var yesterActivityModel: AmountActivityModel?
        if fallAsleepDate.day != awakeDate.day, let activityModel = AmountActivityModel.day(date: fallAsleepDate) {
            // 睡眠跨天
            yesterActivityModel = activityModel
            
        }
        
        let index = awakeDate.hour * 60 + awakeDate.minute
        var activitysRange = Array(activitys[0 ..< index])
        
        if let yesterActivityModel = yesterActivityModel {
            let index = fallAsleepDate.hour * 60 + fallAsleepDate.minute
            var activitys = yesterActivityModel.activitys
            if activitys.count < 1440 {
                let zeros = (activitys.count ..< 1440).map { _ in 0 }
                activitys.append(contentsOf: zeros)
            }
            var addActivitysRange = Array(activitys[index ..< 1440])
            addActivitysRange.append(contentsOf: activitysRange)
            activitysRange = addActivitysRange
        }
        
        return activitysRange
        
    }
    
    func updateData() {
        
        guard let _ = AmountActivityModel.day(date: date) else {
            insert()
            return
        }
        
        update()
        
    }

}
